import { ipcMain, IpcMainInvokeEvent } from "electron";

import { ISession, ITogglePinSessionParams } from "../types/session.ts";
import {
  AddSession,
  GetSessionsByUser,
  HandelUnread,
  SoftDeleteSession,
  TogglePinSession,
  UpdateOrCreateSession,
  UpdateOrCreateSessionList,
  UpdateSessionByField,
} from "../db/servers/session.ts";

export function SessionEvent() {
  // 更新session
  ipcMain.handle(
    "updateSessionByField",
    (_event: IpcMainInvokeEvent, sessionId: string, ownerId: number, data: any) => {
      return UpdateSessionByField(sessionId, ownerId, data);
    },
  );

  ipcMain.handle("UpdateOrCreateSessionList", (_event: IpcMainInvokeEvent, sessionList: ISession[]) => {
    return UpdateOrCreateSessionList(sessionList);
  });

  // 获取本地session
  ipcMain.handle("getLocalSession", (_event: IpcMainInvokeEvent, userId: number) => {
    return GetSessionsByUser(userId);
  });
  // 存储本地session
  ipcMain.handle("storeLocalSession", (_event: IpcMainInvokeEvent, session: ISession) => {
    return UpdateOrCreateSession(session, 0);
  });

  // 置顶session
  ipcMain.handle("togglePinSession", (_event: IpcMainInvokeEvent, params: ITogglePinSessionParams) => {
    return TogglePinSession(params);
  });

  // 删除session
  ipcMain.handle("softDeleteSession", (_event: IpcMainInvokeEvent, sessionId: string, ownerId: number) => {
    return SoftDeleteSession(sessionId, ownerId);
  });

  // 添加session
  ipcMain.handle("addSession", (_event: IpcMainInvokeEvent, session: ISession) => {
    return AddSession(session);
  });

  // 处理未读消息
  ipcMain.handle("handelUnread", (_e: IpcMainInvokeEvent, sessionId: string, ownerId: number) => {
    HandelUnread(sessionId, ownerId);
  });
}
